<?php
/**
 * Created By virus_cms
 * Author: Virus
 * Date: 2020/3/2
 * Time: 17:10
 */

namespace app\admin\service;


use app\common\model\mysql\AuthRule;

class RuleService
{
    protected $ruleModel = null;

    public function __construct()
    {
        $this->ruleModel = new AuthRule();
    }

    /**
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAllTopPermissions()
    {
        $result = $this->ruleModel->getAllTopPermissions();
        if (empty($result)) {
            return [];
        }

        $result = $result->toArray();

        return $result;
    }

    public function addRule($data)
    {
        $result = $this->ruleModel->addRule($data);
        if (false === $result) {
            throw new \think\Exception("配置添加失败");
        }

        return true;
    }

    public function getOneRuleById($id)
    {
        $result = $this->ruleModel->getOneRuleById($id);
        if (empty($result)) {
            return [];
        }

        return $result;
    }

    public function updateRuleById($id, $data)
    {
        $result = $this->ruleModel->updateRuleById($id, $data);
        if (false === $result) {
            throw new \think\Exception("权限编辑失败");
        }

        return true;
    }

    /**
     * @param $id
     * @return bool
     * @throws \think\Exception
     */
    public function deleteById($id)
    {
        // 判断是否拥有子权限
        $son = $this->ruleModel->getSonRuleByPidEquealId($id);
        if ($son > 0) {
            throw  new \think\Exception("该权限下有子权限，无法删除");
        }
        $res = $this->ruleModel->deleteById($id);
        if (false === $res) {
            throw new \think\Exception("权限删除失败");
        }

        return true;
    }
}